package com.team.gateway.filter;

import lombok.Data;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
//过滤器demo  属性配置名+GatewayFilterFactory，参考内置过滤器
@Component
public class DemoGatewayFilterFactory extends AbstractGatewayFilterFactory<DemoGatewayFilterFactory.Config> {
    public static final String TOKEN_KEY = "token";

    public DemoGatewayFilterFactory() {
        super(DemoGatewayFilterFactory.Config.class);
    }

    public List<String> shortcutFieldOrder() {
        return Arrays.asList("token");
    }

    public GatewayFilter apply(DemoGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest().mutate().header(TOKEN_KEY, config.getToken()).build();
                return chain.filter(exchange.mutate().request(request).build());
            }

        };
    }
    @Data
    public static class Config {
        private String token;
    }
}